package cz.cvut.kadledav.paa.knapsack.tasks;

import cz.cvut.kadledav.paa.knapsack.bo.Item;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * User: David Kadlecek
 * Date: 2.10.13
 */
public class BruteForceTask extends ATask{

    protected int[] prices;
    protected int[] weight;
    protected boolean[] actual;
    protected boolean[] maxItems = new boolean[0];

    public void setItems(List<Item> items) {
        prices = new int[items.size()];
        weight = new int[items.size()];
        actual = new boolean[items.size()];
        for (int i = 0; i < items.size(); i++) {
            prices[i] = items.get(i).getPrice();
            weight[i] = items.get(i).getWeight();
        }
    }

    public Set<Integer> getComputedItemsIds() {
        HashSet<Integer> computedIds = new HashSet<>();
        for (int i = 0; i < maxItems.length; i++) {
            if(maxItems[i]){
                computedIds.add(i);
            }
        }
        return computedIds;
    }

    public void compute(){
        compute(actual.length-1,0,0);
    }

    public void compute(int index,int priceInKnapsack,int weightInKnapsack){
        if(index<0){
//            print(actual);
            checkAndSaveMax(priceInKnapsack);
            return;
        }
        actual[index]=true;
        int newWeight = weightInKnapsack+weight[index];
        if(newWeight<=maxAllowedWeight){
            compute(index-1,priceInKnapsack+prices[index],newWeight);
        } else {
            checkAndSaveMax(priceInKnapsack);
        }
        actual[index]=false;
        compute(index-1,priceInKnapsack,weightInKnapsack);
    }

    protected void checkAndSaveMax(int priceInKnapsack) {
        if(priceInKnapsack>maxPrice){
            maxPrice = priceInKnapsack;
            maxItems = Arrays.copyOf(actual,actual.length);
        }
    }

//    private void print(boolean[] items) {
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < items.length; i++) {
//            sb.append(items[i]==true?"1":"0");
//            sb.append(" ");
//        }
//        System.out.println(sb.toString());
//    }
}
